﻿module Sustainalytics.LRTM {

    // LRTM controller
    export class LongRunningTaskManagerController {

        constructor(
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private LongRunningTaskManagerService: LongRunningTaskManagerService) {

            this.$scope['lrtm'] = this;

        }

        // get task instances
        public getTaskInstances(): LongRunningTaskInstance[] {
            var instances = this.LongRunningTaskManagerService.getTaskInstances();

            return instances;
        }

        // cancel task
        public cancelTask(taskInstance: LongRunningTaskInstance) {
            if (!taskInstance.canCancel())
                return;

            this.LongRunningTaskManagerService.deleteTask(taskInstance.status.id);
        }

        // close task
        public closeTask(taskInstance: LongRunningTaskInstance) {
            if (!taskInstance.canClose())
                return;

            this.LongRunningTaskManagerService.deleteTask(taskInstance.status.id);
        }

        // download
        public downloadTask(taskInstance: LongRunningTaskInstance) {
            if (!taskInstance.canDownload())
                return;

            this.LongRunningTaskManagerService.downloadResult(taskInstance.status.id);
        }

        public inProgressCount(): number {
            var cnt = $.grep(this.getTaskInstances(),(el, index) => {
                return !(el.status.taskInstanceStatus == LongRunningTaskInstanceStatusEnum.Failed || el.status.taskInstanceStatus == LongRunningTaskInstanceStatusEnum.Finished);
            }).length;

            return cnt;
        }
        public completedCount(): number {
            var cnt = $.grep(this.getTaskInstances(),(el, index) => {
                return el.status.taskInstanceStatus == LongRunningTaskInstanceStatusEnum.Failed || el.status.taskInstanceStatus == LongRunningTaskInstanceStatusEnum.Finished;
            }).length;

            return cnt;
        }
    }    


    // register controller
    angular.module('Sustainalytics.LRTM').controller('LongRunningTaskManagerController',
        ['$scope', '$q', 'LongRunningTaskManagerService', LongRunningTaskManagerController]);

} 